
// pages/upinfo/upinfo.js
var util = require('../../utils/util')
var DATE = util.formatDate(new Date())
var QQMapWX = require('../../utils/qqmap-wx-jssdk.js');
//var uploadImage = require('../../utils/uploadImg/uploadImgnew.js');//地址换成你自己存放文件的位置
var qqmapsdk = new QQMapWX({
    //key: 'U47BZ-NJBK3-LZB3B-3YAQR-564JQ-XVF7N' // 必填
    //key: '5PNBZ-MTTWQ-HCJ5Z-4FPNH-6H2GT-L3FGT'
    key: 'VZHBZ-6BYWU-WCPVE-2NRJV-YZKXZ-GEFT4'
});
var api = require('../../config/api.js');

//录音
const recorderManager = wx.getRecorderManager()
const innerAudioContext = wx.createInnerAudioContext()

Page({

    /**
     * 页面的初始数据
     */
    data: {

        //推荐区域
       
        suggestTypeItems: [
            { value: 1, code:'cz',name: '川中区域' },
            { value: 2, code:'cx',name: '川西北区域' },
            { value: 3, code:'cd',name: '成都区域' },
            { value: 4, code:'my',name: '绵阳管道部区域' },
            { value: 5, code:'jc',name: '基层管理部' },
            { value: 6, code:'czgb',name: '村镇干部' }
        ],
        indexsuggestType: 0,

        //隐患类型
        hiddenTypeItems: [
            { value: 1, name: '第三方施工' },
            { value: 2, name: '堡坎垮塌' },
            { value: 3, name: '露管' },
            { value: 4, name: '违章施工' },
            { value: 5, name: '故障报修' },
            { value: 6, name: '附属设施问题' },
            { value: 7, name: '管道周边烧（燃）火' },
            { value: 8, name: '重车碾压管道' },
            { value: 9, name: '挖机停靠在管道周边' },
            { value: 10, name: '焚烧菜杆' },
            { value: 11, name: '修坟立碑' },
            { value: 12, name: '修房搭棚挖塘' },
            { value: 13, name: '土地复耕承包流转' },
            { value: 14, name: '漏气' },
            { value: 15, name: '种植深根植物' },
            { value: 16, name: '堆放重物' }
        ],

        //上报信息
        reportInfo: {
            userName: '',
            phone: '',
            hiddenType: 1,
            hiddenRemark: '',
            address: '',
            province: '',
            city: '',
            district: '',
            longitude: 0,
            latitude: 0,
            fliePath: '',
           
            //提交数组
            fliePathImage: [],
            //音频
            soundPath: '',
        },

        indexhiddenType: 0,
        imgList: [],


        //------oss上传所需参数------//
        ossAccessKeyId: '',
        policy: '',
        signature: '',
        //上传图片地址
        imagePathUrl: '',



        //---------音频----------//
        j: 1,//帧动画初始图片
        isSpeaking: false,//是否正在说话
        durationNew: 0,//录音时长
        loadModalSound: false,//播放弹框

    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        //获取地址
        this.getCurrentLocal()
        //获取网络用户名
        // this.getAuth()
        //获取oss上传参数
        this.oss();
        //获取当前数据库用户
        this.inituser();
       

    },

    /**
     * 生命周期函数--监听页面显示
     */

     //检查定位重复
    //  checkUploadLocal(longitude,latitude){
    //      let that=this
    //      let lcoal={ longitude: longitude, latitude: latitude }
    //     util.request(api.getCheckLocal, JSON.stringify(lcoal), 'POST').then(function (res) {
    //         console.log(res)
    //         if (res.code == 200) {
    //             that.bindLocal(res.data)

    //         } else {
    //             util.showErrorToast(res.message);
    //         }

    //     }).catch((err) => {
    //         console.log("登录远程服务器catch:" + err);
    //         //reject(err);
    //     });



    //  },


     //定位提示
     bindLocal(msg){
        wx.showModal({
            title: '温馨提示',
            content: msg,
            success(res) {},
            fail(res) {},
            showCancel: false,
            confirmText: "继续上报", //默认是“确定”
          })

     },

    //初始化用户
    inituser() {
        var userinfo = wx.getStorageSync('userInfoDto');
        console.log(userinfo)
        if (typeof (userinfo.userName) != "undefined") {
            this.setData({
                ['reportInfo.userName']: userinfo.userName,
            })
        }
        if (typeof (userinfo.phone) != "undefined") {
            this.setData({
                ['reportInfo.phone']: userinfo.phone,
            })
        }
        

    },




    //隐患描述
    hiddenRemarkInput(event) {
        this.data.reportInfo.hiddenRemark = event.detail.value
    },

    //拨打电话
    callphone() {
        wx.makePhoneCall({

            phoneNumber: '18090819953',

            success: function (res) {

                console.log(res)

            },

            fail: function (err) {

                console.log(err)

            }

        })
    },


    //-----------录音功能
    //手指按下
    touchdown: function () {
        console.log("手指按下了...")
        console.log("new date : " + new Date)
        var _this = this;
        speaking.call(this);
        this.setData({
            isSpeaking: true
        })
        //开始录音
        const options = {
            duration: 60000,//指定录音的时长，单位 ms
            sampleRate: 16000,//采样率
            numberOfChannels: 1,//录音通道数
            encodeBitRate: 96000,//编码码率
            format: 'mp3',//音频格式，有效值 aac/mp3
            frameSize: 50,//指定帧大小，单位 KB
        }
        //开始录音
        recorderManager.start(options);
        recorderManager.onStart(() => {
            console.log('recorder start')
        });
        //错误回调
        recorderManager.onError((res) => {
            console.log(res);
        })


    },
    //手指抬起
    touchup: function () {
        var that = this;
        console.log("手指抬起了...")
        this.setData({
            isSpeaking: false,
        })
        clearInterval(this.timer)
        //wx.stopRecord()
        recorderManager.stop();
        recorderManager.onStop((res) => {
            console.log('停止录音', res.tempFilePath)
            //获取整数化的录音时长
            var duration = parseInt(res.duration / 1000)
            console.log(parseInt(res.duration / 1000))
            //防止录音时间过短
            if (res.duration < 3000) {
                wx.showToast({
                    title: '录音时间太短，请重新录音',
                    icon: 'none',
                    duration: 1000
                })
            } else if (res.duration > 60000) {
                //防止录音时间过长
                wx.showToast({
                    title: '录音时间过长，请重新录音',
                    icon: 'none',
                    duration: 1000
                })
            } else {
                //判断录音时长是否低于十秒，若低于十秒则加上前置0
                if (duration < 10) {
                    var t = duration
                    duration = t
                }

            }
            //上传录音
            that.uploadfileSound(res.tempFilePath, duration)


        })

    },

    //点击播放录音
    gotoPlay: function (e) {
        var filePath = this.data.reportInfo.soundPath
        console.log("======" + filePath)
        if (filePath.trim() == '' || filePath == null) {
            wx.showToast({
                title: '请先录制',
                icon: 'success',
                duration: 1000
            })
            return

        }
        //点击开始播放
        let that = this
        innerAudioContext.autoplay = true
        innerAudioContext.src = this.data.reportInfo.soundPath,
            innerAudioContext.onPlay(() => {
                console.log('开始播放')
                //speaking.call(that);
                that.setData({
                    loadModalSound: true
                })
            });
        innerAudioContext.onEnded((res) => {
            console.log('播放停止' + res)
            that.setData({
                loadModalSound: false
            })
        });

        innerAudioContext.onError((res) => {
            console.log(res.errMsg)
            console.log(res.errCode)
        })
    },




    //---------------录音结束------------//



    //浏览图片
    ViewImage(e) {
        wx.previewImage({
            urls: this.data.imgList,
            current: e.currentTarget.dataset.url
        });
    },

    ChooseImage() {
        wx.chooseImage({
            count: 4, //默认9
            sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
            sourceType: ['album', 'camera'], //从相册选择
            success: (res) => {
                if (this.data.imgList.length != 0) {
                    this.setData({
                        imgList: this.data.imgList.concat(res.tempFilePaths)
                    })
                } else {
                    this.setData({
                        imgList: res.tempFilePaths
                    })
                }

                //上传
                console.log(res.tempFilePaths[0])
                this.uploadfile(res.tempFilePaths[0])



            }
        });
    },

    DelImg(e) {
        wx.showModal({
            title: '提示',
            content: '确定要删除吗？',
            cancelText: '取消',
            confirmText: '确定',
            success: res => {
                if (res.confirm) {
                    this.data.imgList.splice(e.currentTarget.dataset.index, 1);
                    this.data.reportInfo.fliePathImage.splice(e.currentTarget.dataset.index, 1);
                    this.setData({
                        imgList: this.data.imgList,
                        ['reportInfo.fliePathImage']: this.data.reportInfo.fliePathImage
                    })
                }
            }
        })
    },



    //隐患类型
    bindinputhiddenType(event) {
        let index = event.detail.value;
        this.data.reportInfo.hiddenType = this.data.hiddenTypeItems[index].value
        this.setData({
            indexhiddenType: index
        })
    },

  

    //---------------提交数据----------------------//

    /**
       * 校验
       */
    checkValue() {
        let dataup = this.data;
     
        if (dataup.reportInfo.latitude == 0 || dataup.reportInfo.latitude == null) {
            util.showErrorToast('未获取到正确地址，请稍后再试');
            return false
        }
        if (this.data.localname == '' || this.data.localname == null) {
            util.showErrorToast('未获取到正确地址，请稍后再试');
            return false
        }

        if (dataup.reportInfo.longitude == 0 || dataup.reportInfo.longitude == null) {
            util.showErrorToast('未获取到正确地址，请稍后再试');
            return false
        }

        if (dataup.reportInfo.city == '' || dataup.reportInfo.city == null) {
            util.showErrorToast('未获取到正确地址，请稍后再试');
            return false
        }
        if (dataup.reportInfo.district == '' || dataup.reportInfo.district == null) {
            util.showErrorToast('未获取到正确地址，请稍后再试');
            return false
        }

        if (dataup.reportInfo.province == '' || dataup.reportInfo.province == null) {
            util.showErrorToast('未获取到正确地址，请稍后再试');
            return false
        }

        return true
    },


    //保存提交
    save() {

        if (!this.checkValue()) {
            //this.loadModal();
            return
        }

        // //判断是否选择图片
        // if (this.data.reportInfo.fliePathImage < 1) {
        //     util.showErrorToast("请上传现场图片！");
        //     return
        // }

        if (this.data.reportInfo.soundPath === '' || this.data.reportInfo.soundPath == null) {
            wx.showModal({
                title: '提示',
                content: '是否不现场录音上报信息？',
                cancelText: '取消',
                confirmText: '确定',
                success: res => {
                    if (res.confirm) {
                        this.loadup();
                    }
                }
            })

        }else{
            this.loadup();
        }

    },

    //上报数据
    loadup(){
        //提交上报数据
        let dataup = this.data.reportInfo;
        let that = this;
        console.log(JSON.stringify(dataup))
        that.loadModal();
        util.request(api.reportInfo, JSON.stringify(dataup), 'POST').then(function (res) {
            console.log(res)
            if (res.code == 200) {
                that.closeModal();
                //刷新界面
                console.log("========")
                wx.showModal({
                    title: '上报成功!',
                    content: '感谢您对我们在管道保护工作中的贡献和支持。为此，我们准备了一个小小的奖励作为感谢。让我们携起手来，继续努力在管道保护工作中，共同创造一个安全可靠的生活环境。',
                    confirmText: '确定',
                    success: res => {
                        // wx.reLaunch({
                        //     url: '/pages/report/report'
                        // })
                        wx.navigateBack({})
                    }
                })

            } else {
                util.showErrorToast(res.message);
            }

        }).catch((err) => {
            that.closeModal();
            console.log("登录远程服务器catch:" + err);
            //reject(err);
        });


    },





    //进度条
    loadModal() {
        this.setData({
            loadModal: true
        })
    },
    closeModal() {
        this.setData({
            loadModal: false
        })
    },

    //----------上传文件--------------------//

    /**
       * 初始化参数
       */
    oss() {
        let that = this;
        //发起网络请求
        util.request(api.ossinit, null).then(function (res) {
            console.log("oss"+res)  
            that.setData({
                policy: res.policy,
                ossAccessKeyId: res.ossAccessKeyId,
                signature: res.signature
            })
        }
        ).catch((err) => {
            console.log("远程服务器catch:" + err);
            //reject(err);
        });
    },

    /**
     * 上传文件
     */
    uploadfile(tempFilePath) {
        let that = this;
        const key = new Date().getTime() + Math.floor(Math.random() * 150) + '.png';
        // 上传图片到oss
        wx.uploadFile({
            // 直传的oss地址
            url: 'https://hiddengwb.oss-cn-chengdu.aliyuncs.com',
            // 上传的文件
            filePath: tempFilePath,
            // 必须为file
            name: 'file',
            // 表单数据
            formData: {
                // key：文件路径，如 user/666.png
                //直接 key: "${filename}" 是存放在根目录，文件名为上传的文件名
                // 如果后端签名时指定了dir则开头必须同后端的一致，如后端指定了 “user/” 开头则必须是 user/xxx.xx
                'key': key,
                // 自定义成功响应值 ，默认响应204
                'success_action_status': '200',
                'OssAccessKeyId': this.data.ossAccessKeyId,
                // 后端签名后发回的policy
                'policy': this.data.policy,
                // 后端返回的签名
                'signature': this.data.signature
            },
            success: function (res) {
                wx.hideLoading();
                if (res.statusCode == 200) {
                    console.log("上传成功！")

                    var pathTemp = 'https://hiddengwb.oss-cn-chengdu.aliyuncs.com/' + key;
                    that.data.reportInfo.fliePathImage.push(pathTemp);

                } else {
                    console.log("上传失败！")
                    console.log(res)
                }
            },
            fail(error) {
                console.log("上传错误")
                console.log(error)
            }
        })
    },


    /**
     * 上传音频文件
     * @param {*} tempFilePath 
     */
    uploadfileSound(tempFilePath, duration) {
        let that = this;
        const key = new Date().getTime() + Math.floor(Math.random() * 150) + '.mp3';
        // 上传图片到oss
        wx.uploadFile({
            // 直传的oss地址
            url: 'https://hiddengwb.oss-cn-chengdu.aliyuncs.com',
            // 上传的文件
            filePath: tempFilePath,
            // 必须为file
            name: 'file',
            // 表单数据
            formData: {
                // key：文件路径，如 user/666.png
                //直接 key: "${filename}" 是存放在根目录，文件名为上传的文件名
                // 如果后端签名时指定了dir则开头必须同后端的一致，如后端指定了 “user/” 开头则必须是 user/xxx.xx
                'key': key,
                // 自定义成功响应值 ，默认响应204
                'success_action_status': '200',
                'OssAccessKeyId': this.data.ossAccessKeyId,
                // 后端签名后发回的policy
                'policy': this.data.policy,
                // 后端返回的签名
                'signature': this.data.signature
            },
            success: function (res) {
                wx.hideLoading();
                if (res.statusCode == 200) {
                    console.log("上传成功！")

                    var pathTemp = 'https://hiddengwb.oss-cn-chengdu.aliyuncs.com/' + key;
                    that.setData({
                        ['reportInfo.soundPath']: pathTemp,
                        durationNew: duration
                    })


                } else {
                    console.log("上传失败！")
                    console.log(res)
                }
            },
            fail(error) {
                console.log("上传错误")
                console.log(error)
            }
        })
    },


    //--------------------------地址位置----------//


    //刷新地址
    refreshLocal(e) {

        this.setData({
            modalName: e.currentTarget.dataset.target
        })

        this.getCurrentLocal()
    },
    hideModal(e) {
        this.setData({
            modalName: null
        })
    },



    // 获取当前地理位置 授权验证
    getCurrentLocal() {

        let that = this;
        wx.getSetting({
            success(res) {
                if (res.authSetting['scope.userLocation'] == false) {// 如果已拒绝授权，则打开设置页面
                    wx.openSetting({
                        success(res) {

                        }
                    })
                } else { // 第一次授权，或者已授权，直接调用相关api
                    that.getMyLocation()

                }
            }
        })
    },
    // 获取当前地理位置
    getMyLocation() {
        let that = this

        wx.getLocation({
            type: 'gcj02',
            altitude: true,
            isHighAccuracy: true,
            success(res) {
                that.getlocalname(res.latitude, res.longitude)
                that.setData({
                    modalValue: '刷新定位成功'
                })
            },
            fail(res) {
                that.setData({
                    modalValue: '刷新频率过高'
                })
                console.log(res)
            }
        })
    },

    //获取物理地址
    getlocalname(latitude, longitude) {
        let that = this
        qqmapsdk.reverseGeocoder({
            location: {
                latitude: latitude,
                longitude: longitude
            },
            policy: 1,
            success: function (res) {
                that.data.reportInfo.province = res.result.address_component.province;
                that.data.reportInfo.city = res.result.address_component.city;
                that.data.reportInfo.district = res.result.address_component.district;
                that.data.reportInfo.street = res.result.address_component.street_number;

                that.data.reportInfo.latitude = latitude;
                that.data.reportInfo.longitude = longitude;

                that.data.reportInfo.address = res.result.address + res.result.formatted_addresses.recommend;

                //填入缓存
                that.setData({
                    localname: res.result.address + res.result.formatted_addresses.recommend
                })
                //识别是否有已经定位的信息
                //that.checkUploadLocal(longitude,latitude);

            },
            fail: function (error) {
                console.error(error);
            }
        })
    },


})


//麦克风帧动画
function speaking() {
    var _this = this;
    //话筒帧动画
    var i = 1;
    this.timer = setInterval(function () {
        i++;
        i = i % 5;
        _this.setData({
            j: i
        })
    }, 200);
}